<?php 
if ($this->request['action'] != 'list') return;
?>

<script type='text/javascript' template='<?php echo basename(__FILE__); ?>'>
$(function() {
	$("input.crud_list_filter").live('keyup', refreshTable);
	$("select.crud_list_filter").live('change', refreshTable);
});

var $keyupTimer = null;
function refreshTable($options)
{
	clearTimeout($keyupTimer);
	$keyupTimer = setTimeout(function() {
		var $form = $("#crud_list_form");
		if (!$form.length) {
			$form = $("<form>").attr("id", "crud_list_form").attr("method", "post");
			$("#crud_list").wrapInner($form);
		}

		var $request = new Request('admin', 'crud', 'list');
		$request.setAction('ajax-list');
		if (!$options) $options = {};
		var $params = '';
		if ($options.page) {
			//$request.setParam('page', $options.page);
			$params += 'page=' + $options.page + '&';
		}
		if ($options.order) {
			//$request.setParam('order', $options.order);
			$params += 'order=' + $options.order + '&';
		}
		if ($options.orderType) {
			//$request.setParam('orderType', $options.orderType);
			$params += 'orderType=' + $options.orderType + '&';
		}
		if ($options.perPage) {
			$params += 'perPage=' + $options.perPage + '&';
		}
		
		$(".crud_list_filter").each(function(){
			var $input = $(this);
			var $name = $input.attr("name");
			if ($request.getParam($name)) {
				$request.setParam($name, '');
			}
			
			var $value = $input.attr("value");

			if ($input.attr('multiple')) {
				$value = $input.val();
				for (var $i in $value) {
					$params += $name + '=' + $i + '&';
				}
			} else {
				if (!$name || !$value) return;
				$params += $name + '=' + $value + '&';
			}
		});

		var $url = $request.getUrl();
		var $content = $("#crud_list_content");
		var $paginator = $("#crud_paginator");
		var $count = $("#crud_list_columns").find("th").length;

		$.ajax({
			url: $url,
			dataType: 'json',
			type: 'post',
			data: $params,
			beforeSend: function() {
				$paginator.html("");
				$content.html(
					"<tr><td id='crud_send_status' rowspan='5' colspan='"+$count+"' align='center' valign='center'><img src='' /></td></tr><tr></tr><tr></tr><tr></tr><tr></tr>"
				);
			},
			error: function($request, $status, $error) {
				$("#crud_send_status").attr('align', 'left').html($request.responseText);
			},
			success: function($data) {
				if (document.location.hash) {
					document.location.hash = "#";
				}
				
				HashNavigation.setParams($params);
			
				$paginator.html($data.paginator);
				$content.html($data.content);
				hideControlIndex();

				if (typeof refreshTableCallback != "undefined") {
					refreshTableCallback();
				}

				// Сохраняем полученный при фильтрации URL как lastURL, чтобы потом на него вернуться
				var $lastUrl = 'http://' + document.location.host + document.location.pathname;
				$lastUrl += '?' + $params;
				$.cookie('last_url', $lastUrl, {path: '/'});
			}
			
		});
	}, 700);
}





</script>
